#include "head.h"
int main(int argc, char *argv[])
{
    // ./server 192.168.118.128 1234 3
    ARGS_CHECK(argc,4);
    int workernum = atoi(argv[3]);
    // 分配内存管理每个子进程的信息
    workerdata_t * workerdataArr = (workerdata_t *)calloc(workernum,sizeof(workerdata_t));
    // 创建子进程
    makeWorker(workernum,workerdataArr);
    // tcp服务端的初始化
    int sockfd;
    tcpInit(argv[1],argv[2],&sockfd);
    // 创建epoll文件对象
    int epfd = epoll_create(1);
    // sockfd加入监听
    epollAdd(epfd,sockfd);
    // 每个子进程的pipe加入监听
    for(int i = 0; i < workernum; ++i){
        epollAdd(epfd,workerdataArr[i].pipefd);
    }
    while(1){
        struct epoll_event * readyset = (struct epoll_event *)calloc(workernum+1,sizeof(struct epoll_event));
        int readynum = epoll_wait(epfd,readyset,workernum+1,-1);
        for(int i = 0; i < readynum; ++i){
            if(readyset[i].data.fd == sockfd){
                // 有客户端connect了
                int netfd = accept(sockfd,NULL,NULL);
                for(int j = 0; j < workernum; ++j){
                    if(workerdataArr[j].status == FREE){
                        printf("No %d worker get job!\n",j);
                        sendfd(workerdataArr[j].pipefd,netfd); 
                        workerdataArr[j].status = BUSY;
                        break;
                    }
                }
                // 此处可以使用队列优化。
                close(netfd);//此时父进程关闭无影响
            }
            else{
                // 说明有子进程完成任务
                printf("1 worker finished work!\n");
                for(int j = 0; j < workernum; ++j){
                    if(workerdataArr[j].pipefd == readyset[i].data.fd){
                        pid_t pid;
                        recv(workerdataArr[j].pipefd,&pid,sizeof(pid),0);
                        printf("No %d worker, pid = %d\n", j, pid);
                        workerdataArr[j].status = FREE;
                        break;
                    }
                }
            }
        }
    }
    return 0;
}

